const app = getApp();
Component({
  properties: {
    challengeRule: Object,
    uid: null,
    total: null,
    startTime: null,
    endTime: null,
    totalDay: null,
    overDay: null,
  },
  data: {
    times: [
    //   {
    //   generateTime: "2020-01-08",
    //   matchWay: "step",
    //   sumStep: "1000",
    //   sumKcal: "230",
    //   userId: "123",
    //   finishStatus: "1",
    // }
    ],
    weekDays: [], //周期模板
    // selWeekDay: {},//当前选中的日期
    // currentMonth: 6,//当前月份
  },

  ready: function() {
    const that = this;
    that.getDetail();
  },
  methods: {
    getDetail: function() {
      const that = this;
      const id = that.data.uid || 0;

      app.middleware.requestAjax({
        serAddr: app.serAddrs.selfGetUserMatchTrainRecord,
        data: {
          id
        },
        cancelToast: true,
        success: function(res) {
          that.setData({
            times: res.data
          })
          that.init();
        }
      })
    },
    init: function() {
      const that = this;
      // 初始赋值
      let showMonth = that.data.times[0].generateTime;
      let start = app.middleware.time(0, that.data.startTime || '');
      let end = app.middleware.time(0, that.data.endTime || '');

      that.setData({
        showMonth,
        startTime: `${start.year}/${start.month}/${start.day}`,
        endTime: `${end.year}/${end.month}/${end.day}`
      })

      that.calendarModel();

    },
    /**
     * 日历模板
     */
    calendarModel: function() {
      const that = this;
      const currDate = that.data.currDate;
      const month = that.data.month || 0;
      let selWeekDay = that.data.selWeekDay;
      const times = that.data.times || [];
      let len = times.length + 7;
      // 获取当月1号是星期几
      // let week = that.time(-(that.time().day - 1)).week;
      let tempArr = [];
      // 1号前空白格
      for (let i = 7; i > 0; i--) {
        let tempObj = {};
        // 2018.5.14修改（wx:key值不能为空）
        tempObj.time = that.time(-i).typeB;
        tempObj.day = that.time(-i).day;
        tempObj.year = that.time(-i).year;
        tempObj.month = Number(that.time(-i).month);
        tempObj.week = that.time(-i).week;
        tempObj.weekText = that.time(-i).weekText;
        tempObj.status = 0;
        // 当前月的第几周，周一开始
        if (tempArr.length == 0) {
          tempObj.weekNum = 1;
        } else {
          let weekNum = tempArr[tempArr.length - 1].weekNum || 0;
          if (tempObj.week == 1) weekNum++;
          tempObj.weekNum = weekNum || 1;
        }
        if ((tempArr == 0 && tempObj.week == 1) || tempArr.length > 0) tempArr.push(tempObj);
      }

      len = len - tempArr.length;

      // 日历
      for (let i = 0; i < len; i++) {
        let tempObj = {};
        tempObj.time = that.time(i).typeB;
        tempObj.day = that.time(i).day;
        tempObj.year = that.time(i).year;
        tempObj.month = Number(that.time(i).month);
        tempObj.week = that.time(i).week;
        tempObj.weekText = that.time(i).weekText;
        tempObj.isCurrent = false
        // 每日24点毫秒数是否大于当前毫秒数
        tempObj.status = (that.time(i).msec + that.time().dayMsec) > that.time(0, true).msec ? 1 : 0;
        if (currDate == tempObj.time) {
          tempObj.flag = 1;
          that.setData({
            selTempYear: that.time(i).year,
            selTempMonth: Number(that.time(i).month),
            selTempDay: that.time(i).day,
            selTempWeekText: that.time(i).weekText,
          })
        }
        if (tempObj.month != month) tempObj.status = 0;
        // 当前月的第几周，周一开始
        let weekNum = tempArr[tempArr.length - 1].weekNum || 0;
        if (tempObj.week == 1) weekNum++;
        tempObj.weekNum = weekNum || 1;
        tempArr.push(tempObj);
        if (tempObj.week == 0 && len - i <= 7) break;
      }

      let isToday = false;
      tempArr.forEach((item, index) => {
        if (index == 0 && that.time(0, false, item.time).msec > that.time(0, true).msec) {
          isToday = true;
        }
        times.forEach((childItem, idx) => {
          // 超过今天
          if (isToday) {
            childItem.isFuture = true;
          }
          if (item.time == that.time(0, true).typeB) {
            isToday = true;
            childItem.isToday = isToday;
          }
          // 不在活动计划内，只是凑整
          if ((new Date(times[0].generateTime).getTime()) > (new Date(item.time).getTime()) ||
            (new Date(times[times.length - 1].generateTime).getTime()) < (new Date(item.time).getTime())) {
            // childItem.noScope = true;
            childItem.hasScope = true;
          }
          if (item.time == childItem.generateTime) {
            item = Object.assign(item, childItem)
            // if (!selWeekDay && times.length - 1 == idx) { // 返回了最后一个作为显示
            if (!selWeekDay && 0 == idx) { // 返回了第一个作为显示
              item.isCurrent = true // 作为当前选中的
              selWeekDay = item;
              that.triggerEvent('selectDay', selWeekDay);
            }
          }
        })
        if (!selWeekDay && item.time == that.time(0, true).typeB) {
          selWeekDay = item;
          item.isCurrent = true
          that.triggerEvent('selectDay', selWeekDay);
        }
        console.error('日期：', that.time(0, true).typeB, selWeekDay)

      })

      const total = that.data.total || 0;
      if (selWeekDay.matchWay == 'step') {
        selWeekDay.percent = Number(selWeekDay.sumStep || 0) / Number(total || 0) * 100;
        if (selWeekDay.percent > 100) selWeekDay.percent = 100;
        if (selWeekDay.percent < 0) selWeekDay.percent = 0;
      } else {
        selWeekDay.percent = Number(selWeekDay.sumKcal || 0) / Number(total || 0) * 100;
        if (selWeekDay.percent > 100) selWeekDay.percent = 100;
        if (selWeekDay.percent < 0) selWeekDay.percent = 0;
      }
      console.error(tempArr)
      console.error(selWeekDay)
      that.setData({
        selWeekDay,
        infoData: tempArr,
      })
    },
    /**
     * 选择时间
     */
    changeTime: function(event) {
      var that = this;
      var index = event.currentTarget.dataset.index;
      let infoData = that.data.infoData;
      let selWeekDay = infoData[index];

      if (selWeekDay.isFuture && !selWeekDay.isToday) return;
      if (!selWeekDay.hasScope) return;

      const total = that.data.total || 0;
      if (selWeekDay.matchWay == 'step') {
        selWeekDay.percent = Number(selWeekDay.sumStep || 0) / Number(total || 0) * 100;
        if (selWeekDay.percent > 100) selWeekDay.percent = 100;
        if (selWeekDay.percent < 0) selWeekDay.percent = 0;
      } else {
        selWeekDay.percent = Number(selWeekDay.sumKcal || 0) / Number(total || 0) * 100;
        if (selWeekDay.percent > 100) selWeekDay.percent = 100;
        if (selWeekDay.percent < 0) selWeekDay.percent = 0;
      }

      selWeekDay.isCurrent = true
      that.triggerEvent('selectDay', selWeekDay);

      that.setData({
        selWeekDay: selWeekDay,
        // openCalendar: true,
      })
    },
    /**
     * 日历折叠、打开切换
     */
    changeOpen: function() {
      const that = this;
      const openCalendar = that.data.openCalendar;
      that.setData({
        openCalendar: !openCalendar
      })
    },
    /**
     * 获取年月日
     * params n 与当天时间的差值
     */
    time: function(n = 0, isCurrent, cusTime) {
      const that = this;
      let showMonth = that.data.showMonth;
      let date;

      if (!showMonth || isCurrent) {
        date = new Date();
      } else {
        if (cusTime) {
          date = new Date(cusTime);
        } else {
          date = new Date(showMonth);
        }
      }

      date.setDate(date.getDate() + n);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let week = date.getDay();
      let msec = date.getTime();
      if (month < 10) {
        month = '0' + month;
      }

      let weekText;
      switch (week) {
        case 1:
          weekText = "一";
          break;
        case 2:
          weekText = "二";
          break;
        case 3:
          weekText = "三";
          break;
        case 4:
          weekText = "四";
          break;
        case 5:
          weekText = "五";
          break;
        case 6:
          weekText = "六";
          break;
        case 0:
          weekText = "日";
          break;
      }

      return {
        typeA: month + '月' + day + '日',
        typeB: year + '-' + month + '-' + (day < 10 ? '0' + day : day),
        year: year,
        month: month,
        day: day,
        week: week,
        weekText: weekText,
        msec: msec, //毫秒
        dayMsec: 1000 * 60 * 60 * 24, //一天的毫秒
      };
    },
  },
})